// 管理账号信息
const USERS_KEY: string = 'USERS_KEY';
const RESPONSE_DATASIGN_KEY: string = 'Enjoy-ONLY-MARK';
const CUSTOMER_KEY: string = 'CUSTOMER_KEY';
const cloudServiceAddress: string = "https://www.enjoyit.com.cn:8192"; // 管易通云端服务地址（主）
const cloudServiceAddressBak: string = "http://mbm2.enjoyit.com.cn:8191"; // 管易通云端备用地址（备）
const cloudServiceAddressBak2: string = "http://mbm.enjoyit.com.cn"; // 管易通云端备用地址（备2）

import {type IRequest} from '../types/public'
import dateRangUtil from './dateRangUtil';
import Guid from './guid';
import { Md5 } from 'ts-md5';
import { btoa,atob } from 'js-base64';
import { useMainStore } from '../store/modules/store';
//const mainStore = useMainStore();
// import { useMainStore } from '../../../store/modules/store';
// const mainStore = useMainStore();

// 使用localStorage存储数据
const getLocalStorage = function (key: string):any {
    return getStorageSync(key);
}

const addlocalStorage = function (key: string, value: any): void {
    setStorageSync(key, value)
}

// 使用StorageSync存储数据
const getStorageSync = function (key: string): any {
    const res = uni.getStorageSync(key);
	return res ? JSON.parse(res) : undefined; // 使用类型断言返回一个空对象
}

const setStorageSync = function (key: string, value: any): void {
    uni.setStorageSync(key, JSON.stringify(value));
}

const removeStorageSync = function (key: string): void {
    uni.removeStorageSync(key);
}

const clearStorageSync = function (): void {
    uni.clearStorageSync();
}


// 设置获取密码
interface User {
    account: string;
    password: string;
}

const getUsers = function (): User[] {
    return getStorageSync<User[]>(USERS_KEY) || '[]';
}

const addUser = function (userInfo: User): void {
    let users = getUsers();
    users.push(userInfo);
    setStorageSync(USERS_KEY, users);
}

// 设置获取客户代码 TODO
interface Customer {
    // 根据实际业务逻辑定义Customer接口的属性
}

const getCustomer = function (): Customer[] {
    return getStorageSync<Customer[]>(CUSTOMER_KEY) || '[]';
}

const addCustomer = function (userInfo: Customer): void {
    let customer = getCustomer();
    customer.push(userInfo);
    setStorageSync(CUSTOMER_KEY, customer);
}

interface ILoginInfo {
    sUser: string;
    access_token?: string;
    sTenantId?: string;
}

interface IErrorInfo {
    statusCode?: number;
    errMsg?: string;
}

/**
 * @description     签名数据
 * @param signData  签名数据
 */
const createDataSign = (signData:string,signPrefix:string,uniqueKey?:string,methodName?:string,isBase64?:boolean)=> {
    const newSignKey = signPrefix ? signPrefix : Guid.NewGuid().ToString().substring(0,8).toLocaleLowerCase();
    
    const dateBegin = Date.now();
    const sign = new Md5().appendStr(`${signData}${newSignKey}`).end() as string;
    const dateEnd = Date.now();
  
    const totalMilliseconds = dateEnd-dateBegin;
    if(totalMilliseconds>100) {
      console.log(`服务求数据验签耗时：${totalMilliseconds}毫秒，方法：${uniqueKey||''}-${methodName||''}！`);
    }
  
    const signKey = isBase64 ?  btoa(`${newSignKey}${sign}001`) : sign;
    return signKey;
  }

  const validateDataSignValue = async (rep:any,uniqueKey:string,methodName:string) => {
    const hasSignKey = rep?.header[RESPONSE_DATASIGN_KEY];
    if(hasSignKey) {
      let datasignKey:string = rep?.header[RESPONSE_DATASIGN_KEY] ||'' as string;
      const messageShow = (sign:string,datasignKey:string) => {
        console.error(`${uniqueKey}-${methodName}-数据格式错误`,sign,datasignKey);
        enjoyShowToast('数据格式错误！');
      }
      datasignKey = datasignKey || '';
      if(datasignKey.length<=11) {
        messageShow('',datasignKey);
        return false;
      }
  
      const base64DatasignKey = atob(datasignKey);
      const datasignPrefix = base64DatasignKey.substring(0,8);
      datasignKey = base64DatasignKey.substring(8);
      datasignKey = datasignKey.substring(0,datasignKey.length-3);
      const dateBegin = Date.now();

      const data = rep.data;
      const newSignKey = createDataSign(data,datasignPrefix);
      const dateEnd = Date.now();
  
      const totalMilliseconds = dateEnd-dateBegin;
      if(totalMilliseconds>100) {
        console.log(`服务返回数据验签耗时：${totalMilliseconds}毫秒，方法：${uniqueKey||''}-${methodName||''}！`);
      }
      if(newSignKey!==datasignKey) {
        messageShow(newSignKey,`${base64DatasignKey}-${datasignKey}`);
        return false;
      }
    }
  
    return true;
  }
  

const request = async (req: IRequest, resSuccess:any, resFail: (res: IErrorInfo) => void, timeout: number =30000) => {

    let headers = {
        'Content-Type': 'application/json;charset=utf-8',
        'InvokeUniqueKey': encodeURIComponent(req.data.UniqueKey),
        'InvokeMethod': encodeURIComponent(req.data.MethodName),
    };
	const tokeInfo = {};
	try {
		const mainStore = useMainStore();
		const { loginInfo } = mainStore;
	    const token = loginInfo && loginInfo.sToken ? loginInfo.sToken : '';
	    tokeInfo.Token = token;
	    tokeInfo.UserNo = loginInfo.sUser;
	    tokeInfo.BillType = req.data.BillType;
	    tokeInfo.ClientTime = dateRangUtil.formatDate();
        tokeInfo.IDCode= loginInfo.sUser;
        tokeInfo.TenantIDCode= loginInfo && loginInfo.sTenantId ? loginInfo.sTenantId : '';
	    if (loginInfo  && loginInfo.access_token) {
	        headers['Authorization'] = `Bearer ${loginInfo.access_token}`;
	    }
	} catch (e) {
	    console.log('请求处理异常：', e);
	}

    const reqNew: IRequest['data'] = {
		...tokeInfo,
        ...req.data,
    };

    const url = req.url || (cloudServiceAddress + '/Enjoy/Service');

    console.log('请求方法：' + reqNew.MethodName, '请求URL:', url, '请求参数:', reqNew);

    headers['Enjoy-Uuid-Flag'] = createDataSign(JSON.stringify(reqNew),'',req.data.UniqueKey,req.data.MethodName,true)
    uni.request({
        url,
        data: reqNew,
        dataType: 'string',
        header: headers,
        method: 'POST',
        timeout,
        success: async (res) => {
            console.log('响应方法：' + reqNew.MethodName, '响应数据:', res);
            const validated = await validateDataSignValue(res,reqNew.UniqueKey,reqNew.MethodName);

            if (validated && res.statusCode === 200) {
                const resData = JSON.parse(res.data as string);
                if (resData && resData.HasException) {
                    const { Code } = resData.Exception;
                    if (Code === 'TokenExpired') {
                        const bYesStr = getStorageSync('bTokenExpired');
                        const bYes = bYesStr && JSON.parse(bYesStr) == 'true';
                        if (bYes === false) {
                            setStorageSync('bTokenExpired', 'true');
                            uni.showModal({
                                title: '提示',
                                content: '登录失效，需要重新登录',
                                showCancel: false,
                                success: (res) => {
                                    if (res.confirm) {
                                        setStorageSync("uniIdToken", '');
                                        // mainStore.logout();
                                        // #ifdef APP-PLUS
                                        plus.runtime.restart();
                                        // #endif
                                    }
                                },
                            });
                        }
                        enjoyHideLoading();
                    } else {
						if (resSuccess) {
							resSuccess({
                                ...res,
                                data: resData
                            });
						}
                    }
                } else {
                    if (resSuccess) {
                        resSuccess({
                            ...res,
                            data: resData
                        });
                    }
                }
            } else {
                if (res.statusCode === 401) {
                    uni.showModal({
                        title: '提示',
                        content: '调用接口权限失败，请检查！',
                        showCancel: false,
                        success: (res) => {
                            if (res.confirm) {
                                setStorageSync("uniIdToken", "");
                                // mainStore.logout();
                                uni.reLaunch({
                                    url: '/pages/MainViews/login/login',
                                });
                            }
                        },
                    });
                    enjoyHideLoading();
                } else {
                    uni.showToast({
                        duration: 3500,
                        icon: 'none',
                        title: `访问${url}错误，接口：${reqNew.MethodName}，错误代码：${res.statusCode}`,
                    });
                    setTimeout(() => {
                        if (resFail) {
                            resFail(res);
                        }
                    }, 3500);
                }
            }
        },
        fail: (res:any) => {
            console.log('请求失败：', JSON.stringify(res));
            if (res && res.errMsg) {
                uni.showToast({
                    duration: 3500,
                    icon: 'none',
                    title: '访问服务错误，请联系管理员检查部署配置！地址：' + url + '，接口：' + reqNew.MethodName,
                });
            }
            if (resFail) {
                resFail(res);
            }
        },
    });
};

// 查询服务增加遮罩层
const enjoyShowLoading = function (text?: string): void {
    uni.showLoading({ title: text || "加载中...", mask: true });
}

const enjoyHideLoading = function (): void {
    setTimeout(() => {
        uni.hideLoading();
    }, 500);
}
const enjoyShowToast = ( title:string, duration:number=3500,
                        icon: "none" | "success" | "loading" | "error" | "fail" | "exception" = "none",
                        mask:boolean = true): void => {
        uni.showToast({
            icon,
            title,
            mask,
            duration: duration,
        });
    }


// 设备信息
const getDeviceInfo = () => {
    return uni.getDeviceInfo();
}

export default {
    getUsers,
    addUser,
    getCustomer,
    addCustomer,
    getLocalStorage,
    addlocalStorage,
    getStorageSync,
    setStorageSync,
    removeStorageSync,
    clearStorageSync,
    request,
    enjoyShowLoading,
    enjoyHideLoading,
    cloudServiceAddress,
    cloudServiceAddressBak,
    cloudServiceAddressBak2,
    enjoyShowToast,
    getDeviceInfo
};
